/**
 * @description [transform data]
 * @author duofuni
 */

export const transformToFile = (data, name, type) => {
    return new File([data], name, {
        type,
        lastModified: Date.now()
    })
}

export const urlToBase64 = (img, calback) => {
    const getBase64Image = img => {
        const canvas = document.createElement("canvas")
        canvas.width = img.width
        canvas.height = img.height
        const ctx = canvas.getContext("2d")
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
        const dataURL = canvas.toDataURL()
        return dataURL
    }
    const image = new Image()
    image.crossOrigin = ""
    image.src = img
    if (img) {
        image.onload = () => {
            calback(getBase64Image(image))
        }
    }
}

export const base64ToFile = (base64, fileName) => {
    let arr = base64.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
    }
    return transformToFile(u8arr, fileName, mime)
}

export const createObjectURL = data => {
    return URL.createObjectURL(data)
}